import 'dart:math';
import 'package:flutter/material.dart';
import 'package:ref/ref.dart';
import 'state.dart';

class TestList extends StatelessWidget {
  const TestList({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text('-----测试List类型-----'),
        Wrap(
          children: [
            MvvmDemo01(),
            MvvmDemo02(),
          ],
        )
      ],
    );
  }
}

// -------------------------------------------------------------------------------------------------------
class MvvmDemo01 extends StatefulWidget {
  const MvvmDemo01({Key? key}) : super(key: key);
  @override
  _MvvmDemo01State createState() => _MvvmDemo01State();
}

class _MvvmDemo01State extends State<MvvmDemo01> {
  add() {
    fruitList.set(() {
      fruitList.value.add({
        'title': '水果-${Random().nextInt(100).toString()}',
        'price': Random().nextInt(100),
      });
    });
  }

  minus() {
    fruitList.set(() {
      if (fruitList.value.length <= 0) return false;
      fruitList.value.removeAt(0);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width / 2,
      color: Colors.black.withOpacity(0.1),
      padding: EdgeInsets.all(5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextButton(onPressed: add, child: Text('添加一个')),
          TextButton(onPressed: minus, child: Text('删除一个')),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------------------------------
class MvvmDemo02 extends StatefulWidget {
  const MvvmDemo02({Key? key}) : super(key: key);
  @override
  _MvvmDemo02State createState() => _MvvmDemo02State();
}

class _MvvmDemo02State extends State<MvvmDemo02> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width / 2,
      color: Colors.black.withOpacity(0.2),
      padding: EdgeInsets.all(5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          RefBuilder(
            () => Column(
              children: fruitList.value.map((e) {
                return Text('${e["title"]}----¥${e["price"]}');
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }
}
